package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.feign.clients.ScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.TaskDTO;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private ScheduleClient scheduleClient;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    @Async    //添加任务异步
    public void addNewsToTask(Integer id, Date publishTime) {
        TaskDTO taskDTO = new TaskDTO();

        //设置任务类型
        taskDTO.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        //设置任务优先级
        taskDTO.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //设置任务执行时间
        taskDTO.setExecuteTime(publishTime.getTime());
        //设置任务执行参数
        taskDTO.setParameters(id.toString().getBytes());

        scheduleClient.addTask(taskDTO);

    }


    /**
     * 定时拉取任务,进行文章审核
     */
    @Scheduled(fixedRate = 1000)
    public void scanNewsByTask() {
        log.info("文章审核---消费任务执行---begin---");

        //从list中拉取任务
        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //如果拉取成功
        if (responseResult.getCode() == 200 && responseResult.getData() != null) {
            //将数据转换为task
            String data = JSON.toJSONString(responseResult.getData());
            TaskDTO task = JSON.parseObject(data, TaskDTO.class);
            //取出task里面的parameter，也就是wmnew的id
            String newId = new String(task.getParameters());
            wmNewsAutoScanService.autoScanWmNews(Integer.valueOf(newId));

            log.info("文章审核--消费任务执行---end---");
        }


    }
}
